<template>
  <div class="app-container">
    <el-main>
      <div class="search">
        <el-form ref="searchForm" :inline="true" size="mini" :model="searchForm" class="form-inline">
          <el-form-item label="名称：" prop="name">
            <el-input v-model.trim="searchForm.name" clearable placeholder="请输入名称" />
          </el-form-item>
          <el-form-item label="状态：" prop="status">
            <el-select v-model="searchForm.status" filterable clearable placeholder="请选择状态">
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" plain @click="searchSubmit('searchForm')">搜索</el-button>
            <el-button type="info" plain @click="searchReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-row :gutter="20" type="flex" align="center">
        <el-col>
          <el-button v-permission="'role_add'" type="primary" size="mini" @click.native="showAdd()">新增</el-button>
          <!-- <el-button type="danger" size="small" :disabled="!selectIds.length>0" @click.native="delVer()">删除 </el-button>-->
        </el-col>
      </el-row>

      <el-table ref="multipleTable" size="mini" v-loading="tabLoading" stripe :data="tableData" tooltip-effect="dark" style="width: 100%"
                :row-class-name="tableRowClassName" border :default-sort="{prop: 'date', order: 'descending'}"
                highlight-current-row row-key="id" @selection-change="handleSelectionChange"
      >
        <!-- <el-table-column type="selection" align="center" width="55"></el-table-column> -->
        <el-table-column type="index" label="序号" width="50">
          <template slot-scope="scope">
            <span>{{ (listParams.page - 1) * listParams.page_size + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="角色名称" width="130" show-overflow-tooltip />
        <el-table-column prop="code" label="编码" width="80" show-overflow-tooltip />
        <el-table-column prop="index_page" label="首页" width="130" show-overflow-tooltip />
        <el-table-column prop="memo" label="备注" show-overflow-tooltip />
        <el-table-column prop="sort" label="排序" width="80" show-overflow-tooltip sortable fixed="right" />
        <el-table-column prop="status" label="启用" align="center" width="80" fixed="right">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status" size="mini" v-permission-disabled="'role_switch'" :active-value="1" :inactive-value="0"
                       @change="changeStatus($event,scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px" align="center" fixed="right">
          <template slot-scope="scope">
            <div class="operation">
              <el-button v-permission="'role_edit'" type="primary" icon="el-icon-edit-outline" size="mini"
                         @click.native="showEdit(scope.row)"
              >编辑</el-button>
              <el-button v-permission="'role_del'" type="danger" icon="el-icon-delete" size="mini" :disabled="scope.row.code=='SuperAdministrator' || scope.row.code=='SalesConsultant'" @click.native="delVer(scope.row.id)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页数据 -->
      <el-pagination :current-page.sync="current" :page-sizes="[10, 20, 50, 100, 200, 500]" :page-size="listParams.page_size"
                     layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
      />
    </el-main>

    <el-dialog :close-on-click-modal="false" :title="(cuForm.id?'编辑':'新增')" center :visible.sync="dialogCU" width="95%"
               @close="dialogCUClose('cuForm')"
    >
      <el-form ref="cuForm" v-loading="dialogCULoading" :rules="cuRules" :model="cuForm" label-width="100px" center>
        <el-row class="row-bg">
          <el-col :span="8">
            <el-form-item label="名称" prop="name">
              <el-col :span="24">
                <el-input v-model.trim="cuForm.name" clearable placeholder="请输入名称" />
              </el-col>
            </el-form-item>
            <el-form-item label="编码" prop="code">
              <el-col :span="24">
                <el-input v-model.trim="cuForm.code" clearable :disabled="cuForm.code=='SuperAdministrator' || cuForm.code=='SalesConsultant'" placeholder="请输入编码" />
              </el-col>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-col :span="24">
                <el-radio-group v-model="cuForm.status">
                  <el-radio :label="1">启用</el-radio>
                  <el-radio :label="0">禁用</el-radio>
                </el-radio-group>
              </el-col>
            </el-form-item>
            <el-form-item label="首页" prop="index_page_id">
              <el-cascader v-model="cuForm.index_page_id" clearable class="own-el-cascader" :options="menuList" :props="{'value':'id','label':'label','emitPath':false ,'checkStrictly': false}" />
            </el-form-item>
            <el-form-item label="小程序首页" prop="mini_index_page_id">
              <el-cascader v-model="cuForm.mini_index_page_id" clearable class="own-el-cascader" :options="miniMenuList"
                           :props="{'value':'id','label':'label','emitPath':false ,'checkStrictly': false}"
              />
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-col :span="24">
                <el-input v-model.trim="cuForm.sort" type="number" placeholder="请输入排序" />
              </el-col>
            </el-form-item>
            <el-form-item label="备注" prop="memo">
              <el-col :span="24">
                <el-input v-model.trim="cuForm.memo" clearable type="textarea" :rows="4" maxlength="100" show-word-limit
                          placeholder="备注"
                />
              </el-col>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="web权限">
              <el-tree ref="rightTree" node-key="id" :data="rightsData" :check-strictly="false" :show-checkbox="true"
                       :default-expand-all="true" :expand-on-click-node="false" :check-on-click-node="true" style="max-height: 410px;overflow: auto;" @check-change="checkedChangeRights"
              >
                <span slot-scope="{ node, data }" class="custom-tree-node" style="width:100%">
                  <div class="flex justify-start align-center">
                    <div>
                      <span>{{ data.label }}</span>
                    </div>
                    <div class="margin-left-xs">
                      <span class="text-blue text-own-purple own-tag" style="font-size: 10px;">{{ data.type==2?'':' 菜单 ' }}</span>
                      <!-- <span class="text-orange light own-tag" style="font-size: 10px;">{{ data.type==1?'':' 操作 ' }}</span> -->
                    </div>
                  </div>
                </span>
              </el-tree>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="小程序权限">
              <el-tree ref="miniRightTree" node-key="id" :data="miniRightsData" :check-strictly="false"
                       :show-checkbox="true" :default-expand-all="true" :expand-on-click-node="false" :check-on-click-node="true" style="max-height: 410px;overflow-y: auto;" @check-change="checkedChangeMiniRights"
              >
                <span slot-scope="{ node, data }" class="custom-tree-node" style="width:100%">
                  <div class="flex justify-start align-center">
                    <div>
                      <span>{{ data.label }}</span>
                    </div>
                    <div class="margin-left-xs">
                      <span class="text-blue text-own-purple own-tag" style="font-size: 10px;">{{ data.type==1?' 模块 ':(data.type==2?' 页面 ':(data.type==3?' 功能 ':'')) }}</span>
                    </div>
                  </div>
                </span>
              </el-tree>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click.native="dialogCU=false">取 消</el-button>
        <el-button type="primary" @click.native="onSubmit(cuForm.id)">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import {
  list,
  add,
  edit,
  del,
  change_status,
  check_code_unique,
  detail,
  rights,
  router_rights,
  mini_rights,
  mini_router_rights
} from '@/api/system/role.js'
import {
  Message
} from 'element-ui'
import { isFunction, isTrue, isFalse } from '@/utils/util.js'

export default {
  data() {
    return {
      // search form
      searchForm: {
        name: null,
        status: null
      },
      // page option
      total: null, // 总页数
      current: 1, // 当前页

      // list table
      tableData: [], // 列表数据
      selectIds: [], // 多选选项id

      listParams: {
        name: null,
        status: null,
        page: 1,
        page_size: 10
      }, // list参数
      tabLoading: true,
      // CU dialog
      dialogCULoading: false,
      dialogCU: false, // 增修弹框显示

      cuForm: {
        id: null,
        name: null,
        code: null,
        index_page_id: null,
        mini_index_page_id: null,
        memo: null,
        routerIds: [],
        miniRightIds: [],
        status: 0,
        sort: 1
      },
      cuRules: {
        name: [{
          required: true,
          message: '请输入名称',
          trigger: 'blur'
        }],
        code: [{
          required: true,
          message: '请输入编码',
          trigger: 'blur'
        }],
        index_page_id: [{
          required: true,
          message: '请选择首页',
          trigger: 'change'
        }]
      },

      rightsData: [],
      menuList: [],
      miniRightsData: [],
      miniMenuList: []
    }
  },
  computed: {},
  created() {
    this.getList()
    this.getAllRights()
    this.getMenu()
    this.getMiniAllRights()
    this.getMiniMenu()
  },
  mounted: function() {},
  methods: {
    // 新增弹出框
    showAdd() {
      const that = this
      that.dialogCU = true
      that.dialogCULoading = false
      that.resetForm()
      that.$refs['cuForm'] && this.$refs['cuForm'].resetFields()
      that.setTreeChecked('rightTree', [])
      that.setTreeChecked('miniRightTree', [])
    },
    showEdit(row) {
      const that = this
      const treeKeys = row.routerIds ? row.routerIds.split(',') : []
      const miniTreeKeys = row.miniRightIds ? row.miniRightIds.split(',') : []
      that.cuForm = Object.assign({}, row)
      that.cuForm.routerIds = treeKeys
      that.cuForm.miniRightIds = miniTreeKeys
      that.dialogCU = true
      that.dialogCULoading = false
      that.setTreeChecked('rightTree', treeKeys)
      that.setTreeChecked('miniRightTree', miniTreeKeys)
    },
    // 关闭弹窗
    dialogCUClose(formName) {
      const that = this
      switch (formName) {
        case 'cuForm':
          that.$refs['cuForm'].clearValidate()
          that.resetForm()
          that.setTreeChecked('rightTree', [])
          that.setTreeChecked('miniRightTree', [])
          break
      }
    },

    resetForm() {
      this.cuForm = {
        id: null,
        name: null,
        code: null,
        index_page_id: null,
        mini_index_page_id: null,
        routerIds: [],
        miniRightIds: [],
        memo: null,
        status: 0,
        sort: 1
      }
    },

    setTreeChecked(name, ids, flag = true, checked = true) {
      const that = this
      that.$nextTick(() => {
        if (ids.length > 0) {
          ids.forEach(item => {
            that.$refs['' + name].setChecked(item, checked, false)
          })
        } else {
          if (flag) that.$refs['' + name].setCheckedKeys([])
        }
      })
    },
    // 提交数据 增、改
    onSubmit(id) {
      const that = this
      // 表单校验
      that.$refs.cuForm.validate(valid => {
        // ~ 校验通过
        if (valid) {
          var obj = Object.assign({}, that.cuForm)

          const check_code_params = {
            is_edit: 0,
            code: obj.code
          }
          if (id) {
            check_code_params.id = obj.id
            check_code_params.is_edit = 1
          }

          check_code_unique(check_code_params)
            .then(res => {
              console.log(res)
              if (isTrue(res.data)) {
                Message.error('该编码已存在')
                return false
              }

              // 显示loading
              that.dialogCULoading = true

              obj.routerIds = that.$refs.rightTree.getCheckedKeys().concat(that.$refs.rightTree.getHalfCheckedKeys())
              obj.miniRightIds = that.$refs.miniRightTree.getCheckedKeys().concat(that.$refs.miniRightTree.getHalfCheckedKeys())
              obj.mini_index_page_id = null

              delete obj.created_at
              delete obj.updated_at
              delete obj.deleted_at

              // ~~ 修改
              if (id) {
                that.onEdit(obj)
              } else {
                // ~~ 添加
                delete obj.id
                that.onAdd(obj)
              }
            })
            .catch()
        } else {
          // ~ 不通过
          return false
        }
      })
    },
    // 添加
    onAdd(obj) {
      return add(obj)
        .then(res => {
          const {
            code,
            message
          } = res
          if (code === 200) {
            Message({
              message,
              type: 'success',
              duration: 1000
            })
            this.dialogCU = false
            this.getList()
          }
          this.dialogCULoading = false
        })
        .catch(() => {
          this.dialogCULoading = false
        })
    },

    // 编辑
    onEdit(obj) {
      return edit(obj)
        .then(res => {
          const {
            code,
            message
          } = res
          if (code === 200) {
            Message({
              message,
              type: 'success',
              duration: 1000
            })
            this.dialogCU = false
            this.getList()
          }
          this.dialogCULoading = false
        })
        .catch(() => {
          this.dialogCULoading = false
        })
    },
    // 删除
    delVer(id = false) {
      this.$confirm('确认要删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      })
        .then(() => {
          const ids = id ? [id] : this.selectIds
          del(ids).then(res => {
            const {
              code,
              date,
              message
            } = res
            this.getList()
            Message({
              message,
              type: 'success',
              duration: 1000
            })
          })
        }).catch()
    },
    // 是否启用
    changeStatus(status, row) {
      const flag = +!status
      this.$confirm('确认要' + (status ? '启用' : '禁用') + '?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      })
        .then(() => {
          const ids = [row.id]
          return change_status(ids, status).then(res => {
            const {
              message
            } = res
            Message({
              message,
              type: 'success',
              duration: 1000
            })
          })
        }).catch(() => {
          row.status = flag
        })
    },
    // 获得table列表
    getList() {
      this.tabLoading = true
      return list(this.listParams)
        .then(res => {
          const {
            data: {
              records,
              total
            }
          } = res
          this.tableData = records
          this.total = total
          this.tabLoading = false
        })
        .catch(() => {
          this.tabLoading = false
        })
    },

    getAllRights() {
      return rights().then(res => {
        this.rightsData = res.data
      })
    },
    getMenu() {
      return router_rights().then(res => {
        this.menuList = res.data
      })
    },
    getMiniAllRights() {
      return mini_rights().then(res => {
        this.miniRightsData = res.data
      })
    },
    getMiniMenu() {
      return mini_router_rights().then(res => {
        this.miniMenuList = res.data
      })
    },
    checkedChangeRights(cur, isChecked, obj) {
      const that = this
      /* if (isChecked) {
					if (cur.pids && cur.pids !== '0') {
						that.setTreeChecked('rightTree', cur.pids.split(','), false)
					}
				} else {
					console.log(obj)
					if (!obj) {
						if (cur.cids) {
							that.setTreeChecked('rightTree', cur.cids.split(','), false, false)
						}
					}
				} */
    },
    checkedChangeMiniRights(cur, isChecked, obj) {
      const that = this
      // if (isChecked) {
      //   if (cur.pids && cur.pids !== '0') {
      //     that.setTreeChecked('miniRightTree', cur.pids.split(','), false)
      //   }
      // } else {
      //   if (!obj) {
      //     if (cur.cids) {
      //       that.setTreeChecked('miniRightTree', cur.cids.split(','), false, false)
      //     }
      //   }
      // }
    },
    // 重置搜索表单
    searchReset() {
      this.$refs.searchForm.resetFields()
      const params = this.$refs.searchForm.model
      this.listParams = Object.assign(this.listParams, params)
      this.getList()
    },
    // 搜索
    searchSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const params = this.$refs[formName].model
          if (!params.name) params.name = null
          this.listParams.page = 1
          this.current = 1
          this.listParams = Object.assign(this.listParams, params)
          this.getList()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    // 表单多选
    handleSelectionChange(val) {
      this.selectIds = val.map(item => item.id)
    },
    // 分页 -pageSize改变
    handleSizeChange(val) {
      this.listParams.page_size = val
      this.getList()
    },
    // 分页 -pageNum改变
    handleCurrentChange(val) {
      this.listParams.page = val
      this.getList()
    },
    // 带状态表格
    tableRowClassName({
      row
    }) {
      if (row.status === 0) {
        return 'stop-row'
      }
      return ''
    }
  }
}
</script>
<style scoped>
	.search .el-form-item:last-child {
		margin-left: 35px;
	}

	.el-date-editor>.el-range-separator {
		width: 8% !important;
	}

	.operation button {
		padding: 8px;
	}

	.el-pagination {
		margin-top: 40px;
	}
</style>
<style lang="scss" scoped>
	.app-container {
		.el-table {
			margin-top: 20px;

			.stop-row {}
		}

		.custom-tree-node {
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-size: 14px;
			padding-right: 8px;

			// .own-tag{
			//  padding: 2px;
			//  box-sizing: border-box;
			//  border-radius: 8px;
			//  border: 1px solid $color-blue;
			// }
		}
	}
</style>
